<template>
  <div>
    <a-button type="primary" @click="handleAdd">
      <template #icon>
        <PlusOutlined />
      </template>
      新增选项
    </a-button>
  </div>
  <a-checkbox-group
    :value="value?.split(',') || []"
    @update:value="(v) => handleUpdate(v)"
    style="display: block"
  >
    <a-row
      type="flex"
      style="margin: 8px"
      v-for="(item, index) in options"
      :key="item.key"
    >
      <a-col>
        <a-checkbox :value="item.key">
          <span align="center">选项{{ index + 1 }}</span>
        </a-checkbox>
      </a-col>
      <a-col :flex="1">
        <div style="display: flex">
          <a-input
            v-model:value="item.optionContent"
            style="flex: 1"
            placeholder="请输入选项内容"
          ></a-input>
          <a-button
            danger
            type="primary"
            style="margin-left: 8px"
            @click="handleDelete(item)"
          >
            <template #icon>
              <DeleteOutlined />
            </template>
            删除选项
          </a-button>
        </div>
      </a-col>
    </a-row>
  </a-checkbox-group>
</template>
<script lang="ts" setup>
import { uuid } from "@/utils";
import { onMounted, watch } from "vue";
import type { Option } from "@/api/answer/base-data/exercises/typing";
import type { CheckboxGroupProps } from "ant-design-vue";

interface Props {
  /**答案 */
  value: string;
  /**选项列表 */
  options: Option[];
  /**默认选项数量 */
  optionNum?: number;
}
const props = withDefaults(defineProps<Props>(), {
  optionNum: 4,
});
const emit = defineEmits(["update:value", "update:options"]);

/**新增行 */
const initRow = () => {
  return { optionContent: null, optionId: null, key: uuid() };
};

/**默认选项 */
const defaultOptions = () => {
  return new Array(props.optionNum).fill(null).map(() => initRow());
};

/**更新答案 */
const handleUpdate: CheckboxGroupProps["onUpdate:value"] = (value) => {
  emit("update:value", value.join(",") || null);
};

/**新增选项 */
const handleAdd = () => {
  emit("update:options", [...props.options, initRow()]);
};

/**删除选项 */
const handleDelete = (record: Option) => {
  emit(
    "update:options",
    props.options.filter((f) => f.key != record.key)
  );
};

watch(
  () => props.options,
  (options) => {
    for (const item of options) {
      if (!item.key) {
        item.key = uuid();
      }
    }
  },
  { immediate: true }
);
watch(
  () => props.value,
  (value) => {
    const items = props.options.filter((f) => value?.includes(f.optionId));
    if (items.length) {
      emit("update:value", items.map((m) => m.key).join(","));
    }
  },
  { immediate: true }
);

onMounted(() => {
  if (!props.options || !props.options.length) {
    emit("update:options", defaultOptions());
  }
});
</script>
